package com.cac.demo.service.outStoreRoom;


import com.cac.demo.dao.outStoreRoom.OutStoreroomDao;
import com.cac.demo.service.MsSslShelves.MsSslShelvesService;
import com.cac.demo.util.CreateCommonLog;

import com.cac.demo.util.adapter.ResponseMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class OutStoreMaterialRoomService {

    @Autowired
    private OutStoreroomDao outStoreroomDao;
    @Autowired
    private MsSslShelvesService msSslShelvesService;
    @Autowired
    private OutStoreroomService outStoreroomService;
    @Autowired
    private CreateCommonLog createCommonLog;
    @Value("${pathProperty.isTest}")
    private boolean isTest;

    /**
     * 零件、成品接收叫箱
     */
    public synchronized ResponseMsg callBox(List<HashMap> datas, String ip) {
        ResponseMsg responseMsg = new ResponseMsg();
        List<String> boxLists = new ArrayList<>();
        List<HashMap> itemList = new ArrayList();//剔除大件后的
        int bulky = 0;
        for(HashMap data : datas){
            String itemCode = (String) data.get("itemCode");
            //判断该物料是否为大件物料
            HashMap isBulky = outStoreroomService.isBulkyItems(itemCode);
            if (isBulky == null) {
                itemList.add(data);
            } else {
                data.put("ip", ip);
                outStoreroomService.insertWorkbinDetal(data);
                bulky++;
            }
        }
        //2023-11-07 yebo 判断，非大件的物料只能在接收台叫箱子
        if(itemList.size()>0){//存在非大件的物料
            //判断当前IP是否为接收台,非大件的物料只能在接收台叫箱子
            if(outStoreroomService.checkIsReceConsole(ip)==0){//判断当前位置是否为接收台
                return responseMsg.setRetCode("201").setMessage("叫箱失败,当前接收的物料存在非大件的物料，请确认！非大件物料只能在接收台接收");
            }
        }

        if(itemList.size()==0){
            return responseMsg.setRetCode("200").setMessage("接收成功,其中大件数量为："+bulky+"条");
        }
        for(HashMap item : itemList){
            item.put("ip", ip);
            //1:调用存储过程叫箱
            responseMsg = callProduce(item);
            if (responseMsg.getRetCode().equals("201")) {
                return responseMsg;
            }
            String boxstrs = (String) responseMsg.getResponseBody();
            String[] boxs = boxstrs.split(",");
            //2:重复箱子去重
            for (String box : boxs) {
                if (boxLists.contains(box)) {
                    continue;
                } else {
                    boxLists.add(box);
                }
            }
        }
        log.info(">>>>>>>>>>>>>>>>>>>>>>去重后的箱子："+boxLists.toString());
        //调用存储过程获取要叫的箱子
        //3:创建日志
        responseMsg = createGkLog(boxLists, ip);
        if ("201".equals(responseMsg.getRetCode())) {
            return responseMsg;
        }
        //
        //4:调用流量控制下达任务
        HashMap outFirst = new HashMap();
        String operationBit = null, boxType = "WORKBIN";
        //获取操作位编码
        operationBit = msSslShelvesService.findStartCode(ip, boxType);
        outFirst.put("endCode", "xyssj" + operationBit);
        outFirst.put("func", "receive");
        //调用流量控制类
        HashMap str = createCommonLog.callWCSInterface(outFirst);
        String s = (String) str.get("retCode");
        if (s.equals("200")) {
            return responseMsg.setRetCode("200").setMessage(str.get("msg")+",其中大件数量为:"+bulky+"条");
        } else {
            return responseMsg.setRetCode("201").setMessage((String) str.get("msg"));
        }
    }

    /**
     * 标准件叫箱 aa
     * */
    public synchronized ResponseMsg callBzjBox(List<HashMap> datas, String ip) {
        ResponseMsg responseMsg = new ResponseMsg();
        List<String> boxLists = new ArrayList<>();
        List<HashMap> itemList = new ArrayList();//剔除大件后的
        int bulky = 0;
        for(HashMap data : datas){
            String itemCode = (String) data.get("itemCode");
            //判断该物料是否为大件物料
            HashMap isBulky = outStoreroomService.isBulkyItems(itemCode);
            if (isBulky == null) {
                itemList.add(data);
            } else {
                data.put("ip", ip);
                outStoreroomService.insertWorkbinDetal(data);
                bulky++;
            }
        }
        //2023-11-07 yebo 判断，非大件的物料只能在接收台叫箱子
        if(itemList.size()>0){//存在非大件的物料
            //判断当前IP是否为接收台,非大件的物料只能在接收台叫箱子
            if(outStoreroomService.checkIsReceConsole(ip)==0){//判断当前位置是否为接收台
                return responseMsg.setRetCode("201").setMessage("叫箱失败,当前接收的物料存在非大件的物料，请确认！非大件物料只能在接收台接收");
            }
        }
        if(itemList.size()==0){
            return responseMsg.setRetCode("200").setMessage("接收成功,其中大件数量为："+bulky+"条");
        }
        for(HashMap item : itemList){
            item.put("ip", ip);
            //1:调用存储过程叫箱
            responseMsg = callProduceForBzj(item);
            if (responseMsg.getRetCode().equals("201")) {
                return responseMsg;
            }
            String boxstrs = (String) responseMsg.getResponseBody();
            String[] boxs = boxstrs.split(",");
            //2:重复箱子去重
            for (String box : boxs) {
                if (boxLists.contains(box)) {
                    continue;
                } else {
                    boxLists.add(box);
                }
            }
        }
        log.info(">>>>>>>>>>>>>>>>>>>>>>去重后的箱子："+boxLists.toString());
        //调用存储过程获取要叫的箱子
        //3:创建日志
        responseMsg = createGkLog(boxLists, ip);
        if ("201".equals(responseMsg.getRetCode())) {
            return responseMsg;
        }
        //
        //4:调用流量控制下达任务
        HashMap outFirst = new HashMap();
        String operationBit = null, boxType = "WORKBIN";
        //获取操作位编码
        operationBit = msSslShelvesService.findStartCode(ip, boxType);
        outFirst.put("endCode", "xyssj" + operationBit);
        outFirst.put("func", "receive");
        //调用流量控制类
        HashMap str = createCommonLog.callWCSInterface(outFirst);
        String s = (String) str.get("retCode");
        if (s.equals("200")) {
            return responseMsg.setRetCode("200").setMessage(str.get("msg")+",其中大件数量为:"+bulky+"条");
        } else {
            return responseMsg.setRetCode("201").setMessage((String) str.get("msg"));
        }
    }

    /***
     * 零件、成品存储过程获取箱子
     * */
    public ResponseMsg callProduce(HashMap map) {
        HashMap sqlMap = new HashMap();
        ResponseMsg responseMsg =new ResponseMsg();
        sqlMap.put("i_item_code", map.get("itemCode"));
        sqlMap.put("i_item_qty", map.get("deliveryQty"));
        sqlMap.put("i_ip", map.get("ip"));
        sqlMap.put("i_material_barcode", map.get("barcode"));
        sqlMap.put("i_wms_delivery_plan_id", map.get("wmsDeliveryPlanId"));
        sqlMap.put("o_Return_Int", null);
        sqlMap.put("o_Return_String", null);
        //判断是否测试环境
        if(!isTest){
            //正式环境
            outStoreroomDao.searchWorkbinCode(sqlMap);
        }else {
            //测试环境
            outStoreroomDao.searchWorkbinCodeTest(sqlMap);
        }

        log.info("》》》》》》》》》》》》调用存储过程叫箱返回值："+sqlMap.toString());
        if (sqlMap.get("o_Return_Int").equals(1)) {
            log.info("存储过程报错返回");
            return responseMsg.setRetCode("201").setMessage("当前接收图号"+map.get("itemCode") + ":在"+sqlMap.get("o_Return_String"));
        }
        return responseMsg.setRetCode("200").setResponseBody(sqlMap.get("o_Return_String"));
    }
    /***
     * 标准件存储过程获取箱子
     * */
    public ResponseMsg callProduceForBzj(HashMap map) {
        HashMap sqlMap = new HashMap();
        ResponseMsg responseMsg =new ResponseMsg();
        sqlMap.put("i_ao_code", map.get("barcode"));
        sqlMap.put("i_item_code", map.get("itemCode"));
        sqlMap.put("i_item_qty", map.get("deliveryQty"));
        sqlMap.put("i_ip", map.get("ip"));
        sqlMap.put("i_ck_barcode", map.get("ckBarcode"));
        sqlMap.put("i_wms_delivery_plan_id", map.get("wmsDeliveryPlanId"));
        sqlMap.put("o_Return_Int", null);
        sqlMap.put("o_Return_String", null);
        //判断是否测试环境
        if(!isTest){
            //正式环境
            outStoreroomDao.searchWorkbinCodeForBzj(sqlMap);
        }else {
            //测试环境
            outStoreroomDao.searchWorkbinCodeForBzjTest(sqlMap);
        }

        log.info("》》》》》》》》》》》》调用存储过程叫箱返回值："+sqlMap.toString());
        if (sqlMap.get("o_Return_Int").equals(1)) {
            log.info("存储过程报错返回");
            return responseMsg.setRetCode("201").setMessage("获取箱子异常");
        }
        return responseMsg.setRetCode("200").setResponseBody(sqlMap.get("o_Return_String"));
    }

    public ResponseMsg createGkLog(List<String> outWorkbin, String IP) {
        ResponseMsg responseMsg = new ResponseMsg();
        String operationBit = null;
        String boxType = "WORKBIN";
        operationBit = msSslShelvesService.findStartCode(IP, boxType);
        //生成日志
        for (int j = 0; j < outWorkbin.size(); j++) {
            String workbinCode = outWorkbin.get(j);
            HashMap map2 = new HashMap();
            //缓存箱编码和结束位置
            map2.put("workbinCode", workbinCode);
            map2.put("endCode", operationBit);
            //通过缓存箱编码在货架上找箱子
            HashMap out = outStoreroomService.outStoreroomWorkbin(map2);
            if(Objects.isNull(out)){
                return responseMsg.setRetCode("201").setMessage("此缓存箱："+workbinCode+"不在货架上，请查看日志");
            }
            //判断巷道的状态
            String result = outStoreroomService.isRowOn(out);
            if (result.equals("1")) {
                out.put("taskType", "2");
                out.put("command", "1");
                out.put("boxType", "WORKBIN");
                out.put("IP", IP);
                out.put("result", "receive");
                //获取操作位置编号
                out.put("endCode", "xyssj" + operationBit);
                operationBit = msSslShelvesService.findStartCode(out.get("IP").toString(), (String) out.get("boxType"));
                //创建日志
                HashMap str = createCommonLog.outBound(out);
                String s= (String) str.get("retCode");
                //将已经创建日志的箱子编码在货架表上标记为空:不为空箱
                if ("200".equals(s)) {
                    outStoreroomService.updateMsshevle(map2);
                    responseMsg.setMessage("成功").setRetCode("200");
                } else {
                    return responseMsg.setRetCode("201").setMessage((String) str.get("retMsg"));
                }
            }
        }
        return responseMsg;
    }
}
